<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use think\facade\Request;

class Api extends Controller
{

    /**
     * 获取案例详细信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function caseInfo()
    {
        $id = Request::param('id');

        $case = Db::view('cases', 'id,cid,cover,style AS case_style,housing,area,article_id,building,create_time,view_count')
            ->view('article', 'title,author,tag,summary', 'article.id=cases.article_id', 'LEFT')
            ->view('designer', 'name,appointment_count,nick_name,avatar,type,intro,style', 'designer.id=cases.designer1_id OR designer.id=cases.designer2_id OR designer.id=cases.designer3_id OR designer.id=cases.designer4_id', 'LEFT')
            ->where('cases.id', $id)
            ->find();

        $album = Db::name('cases_img')->where('cid', $case['cid'])->field('id,img_url,intro')->order('sort desc, id desc')->select();

        $case['album'] = $album;

        jsonSuccess($case);
    }

    public function updateLandingData()
    {
        $path = "static/";
        $data = fopen($path . "landingData.txt", "r") or die("error");
        // 得到之前名额数量
        $num = fgets($data);
        if (!is_dir($path)) {
            mkdir($path, 0777);  // 创建文件夹,并给777的权限
        }
        // 得到当前名额数量
        $content = ($num + rand(1, 5));            // 写入内容
        $file = $path . "landingData.txt";      // 写入文件
        file_put_contents($file, $content);

        return $content;
    }

    public function updateCountByCode()
    {
        $code = Request::param('code');
        $count = Request::param('count');
        $openid = Request::param('openid');
        $mobile = Request::param('mobile');

        $channel = 'ZMYJ';

        $newCount = $count;

        if(isset($openid) && !empty($openid) && !empty($mobile)) {
            Db::name('wx_user')->where('channel','like','%' . $channel . '%')->where('openid', $openid)->update(['appointment_mobile' => $mobile, 'appointment_time' => date('Y-m-d H:i:s', time())]);
        }

        if($code === 'wxreply') {
            $newCount = ($count + rand(2, 9));
        } else {
            $newCount = ($count + 1);
        }

        // 得到当前名额数量


        $count = Db::name('count')->where('channel','like','%' . $channel . '%')->where('code', $code)->update(['count' => $newCount, 'update_time' => date('Y-m-d H:i:s', time())]);

        return $newCount;
    }

}
